package com.jch.dm4_promise.examples;

import java.io.File;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class DataSyncTask implements Runnable{

    private final Map<String,String> taskParameters;

    public DataSyncTask(Map<String,String> taskParameters){
        this.taskParameters = taskParameters;
    }

    @Override
    public void run() {
        String ftpServer = taskParameters.get("server");
        String ftpUsername = taskParameters.get("username");
        String password = taskParameters.get("password");
        String serverDir = taskParameters.get("serverDir");

        Future<FTPUploader> ftpClientUtilPromise = FTPUploadPromisor.newFTPUploaderPromise(ftpServer,ftpUsername,password,serverDir);

        generateFileFromDB();

        FTPUploader ftpClientUtil = null;
        try{
            ftpClientUtil = ftpClientUtilPromise.get();
        } catch (InterruptedException e) {
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        uploadFiles(ftpClientUtil);
    }

    private void generateFileFromDB(){
        System.out.println("generating files from database...");
        System.out.println(500);
    }

    private void uploadFiles(FTPUploader ftpClientUtil){
        Set<File> files = retrieveGeneratedFiles();
        for (File file:files){
            try{
                ftpClientUtil.upload(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected Set<File> retrieveGeneratedFiles(){
        Set<File> files = new HashSet<>();
        File currDir = new File("classes/com/jch/dm4_promise/examples");
        for (File f:currDir.listFiles((dir,name) -> new File(dir,name).isFile() && name.endsWith(".class"))){
            files.add(f);
        }
        return files;
    }

}
